package at.fhv.androideightpuzzle.activities;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import at.fhv.androideightpuzzle.R;
import at.fhv.androideightpuzzle.application.IObserverArguments;
import at.fhv.androideightpuzzle.application.MultiPlayerClientController;
import at.fhv.androideightpuzzle.application.MultiPlayerHostController;
import at.fhv.androideightpuzzle.application.exceptions.JoinGameFailedException;
import at.fhv.androideightpuzzle.domain.FinishedPlayer;
import at.fhv.androideightpuzzle.network.ConnectionType;
import at.fhv.androideightpuzzle.network.message.StartPuzzleMessage;

public class LoginActivity extends Activity implements OnClickListener, Observer{

	private LoginActivity _instance = null;
	private String _puzzleId = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);
		
		Button buttonLogin = (Button)findViewById(R.id.btnLogin);
		buttonLogin.setOnClickListener(this);
		
		Button buttonCancel = (Button)findViewById(R.id.btnCancel);
		buttonCancel.setOnClickListener(this);
		
		Spinner spinner = (Spinner)findViewById(R.id.spinnerConnectionsTypes);
		ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.connection_types,android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setSelection(1);
		MultiPlayerClientController.getInstance().addObserver(this);
		
		_instance= this;
	}

	/*
	 * Get the Button and check which has clicked, find and start the right Activty
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View view) {
		if(view instanceof Button) {
			Intent intent = null;
			if(view.getId() == R.id.btnLogin) {
				EditText editUserName = (EditText)findViewById(R.id.editViewUsername);
				EditText editHostname = (EditText)findViewById(R.id.editHostname);
				
				String itemSelected = (String)((Spinner)findViewById(R.id.spinnerConnectionsTypes)).getSelectedItem();
				ConnectionType type = ConnectionType.valueOf(ConnectionType.class, itemSelected);
				
				if((editUserName.getText() != null) && (!editUserName.getText().toString().isEmpty())
						&& (editHostname.getText() != null) && (!editHostname.getText().toString().isEmpty()) && (type != null)) {
					try {
						MultiPlayerClientController.getInstance().joinGame(editUserName.getText().toString(),
								editHostname.getText().toString(), type);
					} catch (JoinGameFailedException e) {
						Context context = getApplicationContext();
						CharSequence text = "Join game failed.";
						
						Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
						toast.show();
					}
				} else {
					Context context = getApplicationContext();
					CharSequence text = "Please fill the textboxes.";
					
					Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
					toast.show();
				}
			} else if(view.getId() == R.id.btnCancel) {
				intent = new Intent(this, MainActivity.class);
			}
			if(intent != null) {
				startActivity(intent);
			}
		}
	}

	public void update(Observable observerable, Object argument) {
		if(observerable instanceof MultiPlayerClientController) {
			if(argument.equals(IObserverArguments.JOIN_SUCCESSFUL)) {
				/*
				Context context = getApplicationContext();
				CharSequence text = "Login succesful.";
				
				Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
				toast.show();
				*/
				Message msg=m_handler.obtainMessage(IHandlerMessageKeys.JOIN_SUCCESSFUL);
				msg.setTarget(m_handler);
				msg.sendToTarget();
			}else if(argument instanceof StartPuzzleMessage) {
				/*
				Intent intent = new Intent(this, PlayPuzzleActivity.class);
				
				intent.putExtra(IntentExtraKeys.IS_MULTI_PLAYER_HOST,false);
				intent.putExtra(IntentExtraKeys.IS_MULTI_PLAYER_CLIENT,true);
				
				startActivity(intent);
				**/
				_puzzleId = ((StartPuzzleMessage)argument).getPuzzleId();
				Message msg=m_handler.obtainMessage(IHandlerMessageKeys.START_PUZZLE);
				msg.setTarget(m_handler);
				msg.sendToTarget();
			}else if(argument.equals(IObserverArguments.SERVER_NOT_AVAILABLE)) {
				Message msg = m_handler.obtainMessage(IHandlerMessageKeys.SERVERNOTAVAILABLE);
				msg.setTarget(m_handler);
				msg.sendToTarget();
			}
		}
	}
	
	public final Handler m_handler=new Handler(){
		
		@Override
		public void handleMessage(Message msg){
			if(msg.what==IHandlerMessageKeys.START_PUZZLE){
				Intent intent = new Intent(_instance, PlayPuzzleActivity.class);
				
				intent.putExtra(IntentExtraKeys.PUZZLE_ID, _puzzleId);
				intent.putExtra(IntentExtraKeys.IS_MULTI_PLAYER_HOST,false);
				intent.putExtra(IntentExtraKeys.IS_MULTI_PLAYER_CLIENT,true);
				
				android.util.Log.d("LoginActivity", "start puzzle");
				startActivity(intent);
			}else if(msg.what == IHandlerMessageKeys.JOIN_SUCCESSFUL) {
				Context context = getApplicationContext();
				CharSequence text = "Login succesful.";
				
				Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
				toast.show();
			}else if(msg.what == IHandlerMessageKeys.SERVERNOTAVAILABLE) {
				Context context = getApplicationContext();
				CharSequence text = "Host not found.";
				
				Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
				toast.show();
			}
			
			super.handleMessage(msg);
		}
	};
}
